<template>
  <div class="order-list">
    <!-- 搜索表单 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="订单号">
        <el-input v-model="searchForm.orderId" placeholder="请输入订单号"></el-input>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="searchForm.orderStatus" placeholder="请选择订单状态" style="width: 200px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="待支付" value="1"></el-option>
          <el-option label="待发货" value="2"></el-option>
          <el-option label="待收货" value="3"></el-option>
          <el-option label="已完成" value="4"></el-option>
          <el-option label="已取消" value="5"></el-option>
          <el-option label="售后中" value="6"></el-option>
          <el-option label="售后完成" value="7"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单列表 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="orderId" label="订单号"></el-table-column>
      <el-table-column prop="consignee" label="收货人"></el-table-column> 
      <el-table-column prop="phone" label="手机号"></el-table-column>    
      <el-table-column prop="totalAmount" label="订单金额">
        <template #default="scope">
          ￥{{ scope.row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column label="收货地址" width="250" prop="addressVo">
        <template #default="scope">
          <span>
            {{ scope.row.addressVo.province }} 
            {{ scope.row.addressVo.city }} 
            {{ scope.row.addressVo.district }} 
            {{ scope.row.addressVo.detail }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态">
        <template #default="scope">
          <span :class="getStatusClass(getStatusText(scope.row.orderStatus))">
            {{ getStatusText(scope.row.orderStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="payMethod" label="支付方式">
        <template #default="scope">
          {{ getPayMethodText(scope.row.payMethod) }}
        </template>
      </el-table-column>
      <el-table-column prop="datetime" label="下单时间"></el-table-column>
      <el-table-column label="操作" width="180px">
  <template #default="scope">
    <div style="display: flex; ">
     <el-button
            size="small"
            @click="handleDetail(scope.$index, scope.row)"
          >
            详情
          </el-button>
    <el-button
      v-if="
        getStatusText(scope.row.orderStatus) === '已完成' ||
        getStatusText(scope.row.orderStatus) === '已取消' ||
        getStatusText(scope.row.orderStatus) === '售后完成'
      "
      size="small"
      type="danger"
      @click="handleDelete(scope.$index, scope.row)"
    >
      删除
    </el-button>
    <el-button
      v-if="getStatusText(scope.row.orderStatus) === '待发货'"
      size="small"
      type="success"
      @click="handleAction(scope.$index, scope.row, '发货')"
    >
      发货
    </el-button>
    <el-button
      v-if="getStatusText(scope.row.orderStatus) === '售后中'"
      size="small"
      type="warning"
      @click="handleAfterSale(scope.$index, scope.row)"
    >
      售后
    </el-button>
  </div>
  </template>
</el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="售后详情" width="40%">
      <el-form label-position="top">
        <el-form-item label="用户退货理由">
          <el-input v-model="refundReason" :rows="3" type="textarea" readonly />
        </el-form-item>

        <!-- 拒绝理由输入框 - 始终显示 -->
        <el-form-item label="拒绝理由（同意退货请忽略）">
          <el-input v-model="rejectReason" :rows="2" type="textarea" placeholder="请输入拒绝理由"/>
        </el-form-item>

        <el-form-item >
          <el-button type="danger" @click="handleRefund">同意退货</el-button>
          <el-button type="primary" @click="handleReject">拒绝退货</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="60%">
  <el-table :data="orderItems" border style="width: 100%">
    <el-table-column prop="booktitle" label="书名"></el-table-column>
    <el-table-column prop="bookcover" label="封面">
      <template #default="scope">
        <img :src="scope.row.bookcover" alt="Book Cover" style="max-width: 100px;">
      </template>
    </el-table-column>
    <el-table-column label="单价">
      <template #default="scope">
        ￥{{ scope.row.price }}
      </template>
    </el-table-column>
    <el-table-column prop="quantity" label="数量"></el-table-column>
  </el-table>
</el-dialog>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="total">
    </el-pagination>
  </div>
</template>

<script setup>
import { ref,onMounted } from 'vue'
import{  ElMessage,ElMessageBox } from 'element-plus'
import axios from 'axios'
axios.defaults.baseURL = "http://localhost:8080"

// 表格数据
const tableData = ref([])

// 搜索条件
const searchForm = ref({
  orderId: '',
  orderStatus: ''
})

const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
// 状态映射
const statusMap = {
  1: '待支付',
  2: '待发货',
  3: '待收货',
  4: '已完成',
  5: '已取消',
  6: '售后中',
  7: '售后完成'
};
// 获取状态文本
const getStatusText = (statusCode) => {
  return statusMap[statusCode] || '未知状态';
}
// 状态类名映射
const getStatusClass = (status) => {
  switch (status) {
    case '待支付':       return 'status-pending-payment'   
    case '待发货':       return 'status-awaiting-shipment' 
    case '待收货':       return 'status-awaiting-receipt'  
    case '已完成':       return 'status-completed'         
    case '已取消':       return 'status-canceled'          
    case '售后中':       return 'status-after-sales'       
    case '售后完成':     return 'status-after-sales-done'  
    default:             return ''
  }
}
// 支付方式映射
const payMethodMap = {
  1: '支付宝',
  2: '微信',
  3: '银行卡'
};
// 获取支付方式文本
const getPayMethodText = (payMethodCode) => {
  return payMethodMap[payMethodCode] || '未知支付方式';
}
// 获取订单列表
const getOrderList = async (params = {}) => {
  try {
     const token = sessionStorage.getItem('token');
    const res = await axios.get('/adminOrder/list', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        ...params
      }, 
      headers: {
    Authorization: `${token}`
      }
    })

    console.log('接口返回的完整数据:', res.data); 
    if (res.data.code === 0) {
      const data = res.data.data
      tableData.value = data.records || []
      total.value = data.total
    } else {
      ElMessage.error('获取订单列表失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('网络错误，请稍后再试')
  }
}
//更新订单状态
const handleAction = async (index, row, action) => {
  console.log('执行操作:', index, row, action)
  let newStatus = null;

  // 根据 action 确定新的状态值
  switch (action) {
    case '发货':
      newStatus = 3; // 设置为待收货
      break;
    default:
      console.error('未知操作:', action);
      return;
  }

  try {
    const token = sessionStorage.getItem('token');
    const res = await axios.get('/adminOrder/UpdateOrderStatus', {
      params: {
        orderId: row.orderId,
        status: newStatus
      },
      headers: {
        Authorization: `${token}`
      }
    });

    if (res.data.code === 0) {
      ElMessage.success('操作成功');
      getOrderList(); // 刷新订单列表
    } else {
      ElMessage.error('操作失败');
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('网络错误，请稍后再试');
  }
}
// 搜索功能
const handleSearch = () => {
   const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value
  };

  if (searchForm.value.orderId) {
    params.keyword = searchForm.value.orderId;
  }

  if (searchForm.value.orderStatus) {
    params.status = parseInt(searchForm.value.orderStatus, 10);
  }

  getOrderList(params);
};

// 重置功能
const resetForm = () => {
  searchForm.value = {
    orderId: '',
    orderStatus: ''
  }
  getOrderList()
}
// 删除订单
const handleDelete = async (index, row) => {
  try {
    // 弹出确认框
    const confirmResult = await ElMessageBox.confirm(
      '此操作将永久删除该订单, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    if (confirmResult === 'confirm') {
      const token = sessionStorage.getItem('token');
      const res = await axios.get('/adminOrder/deleteOrderById', {
        params: {
          orderId: row.orderId
        },
        headers: {
          Authorization: `${token}`
        }
      });

      if (res.data.code === 0) {
        ElMessage.success('删除成功');
        getOrderList();
      } else {
        ElMessage.error(res.data.message);
      }
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('请求失败:', error);
      ElMessage.error('网络错误，请稍后再试');
    }
  }
}

const detailDialogVisible = ref(false) 
const orderItems = ref([]) 
// 查看详情
const handleDetail = (index, row) => {
  orderItems.value = row.orderitems || [] 
  detailDialogVisible.value = true 
}

// 分页功能
const handleSizeChange = (val) => {
  pageSize.value = val
  getOrderList()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getOrderList()
}

// 售后弹窗相关
const dialogVisible = ref(false)
const selectedOrder = ref(null)
const refundReason = ref('')
const rejectReason = ref('')
const afterSaleDetail = ref(null)

// 获取售后详情
const getAfterSaleDetail = async (orderId) => {
  try {
    const token = sessionStorage.getItem('token');
    const res = await axios.get('/adminOrder/getRetResult', {
      params: {
        orderId
      },
      headers: {
        Authorization: `${token}`
      }
    });

    if (res.data.code === 0) {
      const data = res.data.data;
      refundReason.value = data.reason; 
      return data;
    } else {
      ElMessage.error(res.data.message || '获取售后详情失败');
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('网络错误，请稍后再试');
  }
}

// 售后按钮点击事件
const handleAfterSale = async(index, row) => {
  selectedOrder.value = row
  dialogVisible.value = true
  refundReason.value = '' // 先清空上次的内容
  // 获取售后详情并显示申请原因
  const detail = await getAfterSaleDetail(row.orderId)
  afterSaleDetail.value = detail ? { ...detail } : null

  if (detail && detail.reason) {
    refundReason.value = detail.reason
  } 
  rejectReason.value = '' 
}
// 处理同意退货
const handleRefund = async () => {
  if (!selectedOrder.value) {
    ElMessage.warning('请选择要处理的订单');
    return;
  }

  try {
    const aftersales = {
      ...afterSaleDetail.value,
      adminAgreement: 1,  
      adminReason: ''      
    };

    const token = sessionStorage.getItem('token');
    const res = await axios.post('/adminOrder/UpdateRetResult', aftersales, {
      headers: {
        Authorization: `${token}`
      }
    });

    if (res.data.code === 0) {
      ElMessage.success('同意退货成功，订单状态已更新为售后完成');
      dialogVisible.value = false;
      getOrderList(); 
    } else {
      ElMessage.error(res.data.message || '同意退货失败');
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('网络错误，请稍后再试');
  }
};

// 处理拒绝退货
const handleReject = async () => {
  if (!rejectReason.value.trim()) {
    ElMessage.warning('请填写拒绝理由');
    return;
  }

  if (!selectedOrder.value) {
    ElMessage.warning('请选择要处理的订单');
    return;
  }

  try {
    const aftersales = {
      ...afterSaleDetail.value,
      adminAgreement: 0,  
      adminReason: rejectReason.value      
    };
   
    const token = sessionStorage.getItem('token');
    const res = await axios.post('/adminOrder/UpdateRetResult', aftersales, {
      headers: {
        Authorization: `${token}`
      }
    });

     console.log('拒绝退货数据:', aftersales);
    if (res.data.code === 0) {
      ElMessage.success('拒绝退货成功');
      dialogVisible.value = false;
      getOrderList(); 
    } else {
      ElMessage.error(res.data.message || '拒绝退货失败');
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('网络错误，请稍后再试');
  }
};

onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.order-list {
  padding: 20px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.status-pending-payment { color: orange; }        /* 待支付 */
.status-awaiting-shipment { color: blue; }        /* 待发货 */
.status-awaiting-receipt { color: darkblue; }     /* 待收货 */
.status-completed { color: green; }              /* 已完成 */
.status-canceled { color: gray; }                /* 已取消 */
.status-after-sales { color: purple; }           /* 售后中 */
.status-after-sales-done { color: pink; }        /* 售后完成 */
</style>
